package org.example.test_03.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.util.NestedServletException;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//注册组件
public class JWTUtil {
    /**
     * 生成token
     * @param userId  用户ID
     */
    public static String createToken(int userId) {

        Calendar instance = Calendar.getInstance();
        // 20秒后令牌token失效
        instance.add(Calendar.SECOND, 24*60*60);

        String token = JWT.create()
                .withClaim("userId", userId)
                .withExpiresAt(instance.getTime()) // 指定令牌的过期时间
                .sign(Algorithm.HMAC256("zheshijiamizifuchuan"));//签名

        return token;
    }

    /**
     * 校验token
     * @param token  token
     * @return
     */
    public static String checkToken(String token){
        try{
            // 通过签名生成验证对象
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("zheshijiamizifuchuan")).build();

            DecodedJWT verify = jwtVerifier.verify(token);
            System.out.println(verify.getClaim("userId"));
//            System.out.println("令牌过期时间："+verify.getExpiresAt());
            return verify.getClaim("userId").toString();
        }catch (Exception exception){
            exception.printStackTrace();
            return null;
        }

    }

}

